<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>

      </el-col>
      <el-col :span="18" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
          label-width="100px"
        >
          <el-form-item label="员工姓名" prop="customerName">
            <el-input
              v-model="queryParams.customerName"
              placeholder="请输入员工姓名"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="员工电话" prop="customerName">
            <el-input
              v-model="queryParams.customerPhone"
              placeholder="请输入员工电话"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['web:CustomerRepair:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['web:CustomerRepair:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['web:CustomerRepair:remove']"
            >删除
            </el-button>
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="CustomerRepairList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="60" align="center" />
          <el-table-column
            label="用户ID"
            align="center"
            prop="customerId"
            v-if="false"
          />

          <!--      展示表格-->
          <el-table-column width="150" label="姓名" align="center" prop="remark" />
          <el-table-column width="120" label="电话" align="center" prop="phonenumber" />
          <el-table-column width="120" label="部门" align="center" prop="dept.deptName" />
          <el-table-column width="120" label="所属供电所" align="center" prop="customerAddress1" />
          <el-table-column label="职位" align="center" prop="postIds" />
          <el-table-column label="角色" align="center" prop="roles" />

          <el-table-column
            width="120"
            fixed="right"
            label="操作"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="Delete"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['web:CustomerRepair:remove']"
              >编辑
              </el-button>
              <el-button
                type="text"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['web:CustomerRepair:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>


    <!-- 添加或修改客户报修抢修对话框 -->
    <el-dialog title="新增员工" :visible.sync="open" width="760px" append-to-body>
      <el-form
        ref="supplyRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="地区" prop="region">
              <v-distpicker  v-model="form.region" province="云南省" :city="form.city" :area="form.area" placeholder="请选择地区"></v-distpicker>
<!--              <el-input v-model="form.nickName" placeholder="请选择地区" maxlength="30" />-->
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="州市供电局名称" prop="stateName">
              <el-input v-model="form.stateName" placeholder="请输入州市供电局名称" />
            </el-form-item>

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="区县供电局名称" prop="districtName">
              <el-input v-model="form.districtName" placeholder="请输入区县供电局名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供电所名称" prop="supplyName">
              <el-input v-model="form.supplyName" placeholder="请输入供电所名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="公司地址" prop="companyAddress">
              <el-input
                v-model="form.companyAddress"
                type="textarea"
                placeholder="请输入公司地址"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm"
          >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script type="text/javascript" name="CustomerRepair">
import moment from 'moment'
import VDistpicker from 'v-distpicker'
import {
  listCustomerRepair,
  getCustomerRepair,
  delCustomerRepair,
  addCustomerRepair,
  updateCustomerRepair, getAllDepts, FrimUser, designate
} from '@/api/web/CustomerRepair'
// import useUserStore from '@/store/modules/user'
import { deptTreeSelect, getUserProfile, listUser } from '@/api/system/user'
import { listDept } from '@/api/system/dept'
import Treeselect from "@riophae/vue-treeselect";

export default {
  name: "Dispatch",
  components: {Treeselect, VDistpicker },
  dicts: ['sys_flag','sys_fp'],
  data() {
    return {
      deptOptions: [], // 部门树选项
      deptName: undefined,   // 部门名称
      defaultProps: {
        children: "children",
        label: "label"
      },
      order: {},
      dialogVisible: false,
      btnLoading: false,
      bLoad: false,
      frims: [],
      users: [],
      sys_fp: [],
      sys_flag: [],
      CustomerRepairList: [],
      open: false,
      buttonLoading: false,
      loading: true,
      showSearch: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: '',
      form: {
        province: '云南省',
        city: '',
        area: ''
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supplyName: undefined,
      },
      rules: {
        region: [
          { required: true, message: "用户ID不能为空", trigger: "change" },
        ],
        // deptId: [
        //   { required: true, message: "归属部门不能为空", trigger: "change" },
        // ],
        stateName: [
          { required: true, message: "州市供电局名称不能为空", trigger: "blur" },
        ],
        districtName: [
          { required: true, message: "区县供电局名称不能为空", trigger: "blur" },
        ],
        supplyName: [
          { required: true, message: "供电所名称不能为空", trigger: "blur" },
        ],
        // customerKey: [{ required: true, message: "主键不能为空", trigger: "blur" }],
      }
    }
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  watch: {
    // dialogVisible(newValue) {
    //   if (newValue) {
    //     //getAllDepts-js路径
    //     getAllDepts({ parentId: 100 }).then(res => {
    //       // console.log(res, this.treeData(res.data), 'hhjhj')
    //       const arr = []
    //       res.data.forEach((item, index) => {
    //         if (item.parentId == 100) {
    //           res.data[index].label = item.deptName
    //           res.data[index].value = item.deptId
    //           arr.push(item)
    //         }
    //       })
    //
    //       this.frims = arr
    //     })
    //   }
    // },
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    /** 查询客户报修抢修列表 */
    getList(query) {
      // console.log(this.queryParams)
      // console.log(query)
      this.loading = true;
      listUser(this.addDateRange(this.queryParams)).then(response => {
          this.CustomerRepairList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
      // listCustomerRepair(this.queryParams).then((response) => {
      //   console.log(response, '111')
      //   this.CustomerRepairList = response.rows;
      //   this.total = response.total;
      //   this.loading = false;
      // });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        customerId: null,
        supplyName: null,
      };
      this.resetForm("supplyRef");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryRef");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.customerKey);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      console.log('wwewe')
      this.reset();
      this.open = true;
      listDept(this.queryParams).then(response => {
        console.log(response)
        if (response.resultCode == 200) {
          this.deptOptions = response.data
        }
        // this.deptList = this.handleTree(response.data, "deptId");
        // this.loading = false;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const customerKey = row.customerKey || this.ids;
      getCustomerRepair(customerKey).then((response) => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["supplyRef"].validate((valid) => {
        console.log(this.form)
        if (valid) {
          this.buttonLoading = true;
          if (this.form.customerKey != null) {
            updateCustomerRepair(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addCustomerRepair(form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(row, '数据项')
      let that = this
      const customerKeys = row.customerKey || this.ids;
      this.$modal
        .confirm(`是否确认删除编号为：${customerKeys}的【${row.customerHelp}】？`)
        .then(function () {
          that.loading = true;
          return delCustomerRepair(customerKeys);
        })
        .then(() => {
          that.loading = true;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .finally(() => {
          that.loading = false;
        });
    },
    handleDisplay(row) {
      this.dialogVisible = true
      this.order = row
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "web/CustomerRepair/export",
        {
          ...this.queryParams,
        },
        `CustomerRepair_${new Date().getTime()}.xlsx`
      );
    },
    // 处理部门数据
    treeData (source, id = 'deptId', parentId= 'parentId', children= 'children', rootId) {
      const newRootId = rootId || (source && source.length > 0 && source[0].parentId) || '100'
      console.log(newRootId, 'r4554545')
      if (source.length !== 0) {
        return source.filter((father) => {
          father.label = father.deptName
          father.value = father.deptId
          const parent = father
          // console.log(parent, parent[id], '数据库')
          // const branchArr = source.filter(child => parent[id] === child[parentId])// 返回每一项的子级数组
          const branchArr = source.filter(child => father.deptId == child.parentId)// 返回每一项的子级数组
          // console.log(branchArr, '哈哈哈')
          if (branchArr.length > 0) {

            parent[children] = branchArr
            // parent.children = branchArr
          } else {
            delete parent[children]
            // delete parent.children// 如果存在子级，则给父级添加一个children属性，并赋值
          }
          // return parent[parentId] === newRootId // 返回第一层
          return parent.parentId == newRootId // 返回第一层
        })
      }
    }

  }
}
</script>
